package com.sjgtw.cloud.web.organization.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.organization.domain.Organization;
import com.sjgtw.cloud.web.organization.domain.OrganizationDetails;
import com.sjgtw.cloud.web.organization.mapper.OrganizationDetailsMapper;
import com.sjgtw.cloud.web.organization.mapper.OrganizationMapper;
import com.sjgtw.cloud.web.organization.service.IOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.groupingBy;

/**
 * 应急组织管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-15
 */
@Service
public class OrganizationServiceImpl implements IOrganizationService
{
    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private OrganizationDetailsMapper organizationDetailsMapper;

    @Autowired
    private RedisService redisService;


    /**
     * 查询应急组织管理
     * 
     * @param id 应急组织管理主键
     * @return 应急组织管理
     */
    @Override
    public Organization selectOrganizationById(Long id)
    {
        return organizationMapper.selectOrganizationById(id);
    }

    /**
     * 查询应急组织管理列表
     * 
     * @param organization 应急组织管理
     * @return 应急组织管理
     */
    @Override
    public JSONArray selectOrganizationList(Organization organization)
    {

        List<Map<String,Object>> organizationList = organizationMapper.selectOrganizationList(organization);

        JSONArray array = new JSONArray();

        if(organizationList.size()>0){

            for (Map<String,Object> o : organizationList) {

                JSONObject jsonObject = JSONObject.parseObject(String.valueOf(JSON.toJSON(o)));

                Long organizationId = (Long) o.get("id");

                List<Map<String,Object>> organizationDetailsList = organizationDetailsMapper.selectOrganizationDetailsByOrganizationId(organizationId);

                Map<Object, List<Map<String, Object>>> collect = organizationDetailsList.stream().collect(groupingBy(item -> item.get("groupNumber")));

                HashMap<Object, Object> result = new HashMap<>();
                if(collect!=null){
                    collect.forEach((k, v) -> {
                        System.out.println(k + " = " + v);
                        result.put(k,v);
                        v.stream().forEach(item -> {
                            System.out.println("item = " + item);
                        });
                    });
                }
                jsonObject.put("details",result);
                array.add(jsonObject);
            }
        }

        return array;
    }

    /**
     * 新增应急组织管理
     * 
     * @param organization 应急组织管理
     * @return 结果
     */
    @Override
    public JSONObject insertOrganization(Organization organization)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        organization.setCreateBy(user.getUsername());
        organization.setCreateTime(DateUtils.getNowDate());
        organizationMapper.insertOrganization(organization);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("organizationId",organization.getId());
        return jsonObject;
    }

    @Override
    public int addDetails(JSONObject details) {

        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        //1. 先把旧的删除
        Long organizationId = details.getLong("organizationId");
        String commander = details.getString("commander");
        String deputyCommander = details.getString("deputyCommander");

        Organization organization = new Organization();
        organization.setId(organizationId);
        organization.setCommander(commander);
        organization.setDeputyCommander(deputyCommander);
        organization.setUpdateTime(new Date());
        organizationMapper.updateOrganization(organization);


        JSONObject detailsMap = details.getJSONObject("detailsMap");
        if(detailsMap != null){
            organizationDetailsMapper.deleteOrganizationDetailsByOrganizationId(organizationId);
            Map json = (Map) JSONObject.parse(JSONObject.toJSONString(detailsMap));
            if (json.size()>0){
                for (Object map : json.entrySet()){
                    String group = (String) ((Map.Entry) map).getKey();
                    String arrayString = String.valueOf(((Map.Entry) map).getValue());

                    JSONArray detailsList = JSONArray.parseArray(arrayString);
                    if(detailsList.size()>0){
                        for (int i = 0; i < detailsList.size(); i++) {
                            JSONObject detailsParams = (JSONObject) detailsList.get(i);
                            OrganizationDetails organizationDetails = new OrganizationDetails();
                            organizationDetails.setOfficeName(detailsParams.getString("officeName"));
                            organizationDetails.setCreateBy(user.getUsername());
                            organizationDetails.setCreateTime(new Date());
                            organizationDetails.setGroupNumber(Integer.valueOf(group));
                            organizationDetails.setOrganizationId(organizationId);
                            organizationDetails.setUserId(detailsParams.getString("userId"));
                            organizationDetails.setPosition(detailsParams.getString("position"));
                            organizationDetailsMapper.insertOrganizationDetails(organizationDetails);
                        }
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 修改应急组织管理
     * 
     * @param organization 应急组织管理
     * @return 结果
     */
    @Override
    public int updateOrganization(Organization organization)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        organization.setUpdateBy(user.getUsername());
        organization.setUpdateTime(DateUtils.getNowDate());
        return organizationMapper.updateOrganization(organization);
    }

    /**
     * 批量删除应急组织管理
     * 
     * @param ids 需要删除的应急组织管理主键
     * @return 结果
     */
    @Override
    public int deleteOrganizationByIds(Long[] ids)
    {
        return organizationMapper.deleteOrganizationByIds(ids);
    }

    /**
     * 删除应急组织管理信息
     * 
     * @param id 应急组织管理主键
     * @return 结果
     */
    @Override
    public int deleteOrganizationById(Long id)
    {
        organizationDetailsMapper.deleteOrganizationDetailsByOrganizationId(id);
        return organizationMapper.deleteOrganizationById(id);
    }

    @Override
    public int deleteDetails(Long id) {
        return organizationDetailsMapper.deleteOrganizationDetailsByOrganizationId(id);
    }
}
